package com.tungse.study.rpc.framework;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tungse.study.rpc.framework.entity.Invocation;
import com.tungse.study.rpc.framework.entity.RpcUri;
import com.tungse.study.rpc.framework.protocol.HttpClient;
import com.tungse.study.rpc.framework.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author Tungse
 */
public class RpcProxy {


    public static <T> T createProxy(Class<T> clazz) {


        return (T)Proxy.newProxyInstance(RpcProxy.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //
                Invocation invocation = new Invocation(clazz.getName(), method.getName(), method.getParameterTypes(), args);

                //服务发现， 获取注册的服务地址信息
                List<RpcUri> serviceUri = RemoteMapRegister.getServiceUri(clazz.getName());
                RpcUri rpcUri = LoadBalance.getServiceUri(serviceUri);

                //调用rpc服务
                String result = HttpClient.send(rpcUri.getHostname(), rpcUri.getPort(), invocation);

                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(result, method.getReturnType());
            }
        });
    }
}
